package com.sfac.hqyj.springBoot.modules.common.service.impl;

import com.sfac.hqyj.springBoot.modules.common.dao.ExceptionLogDao;
import com.sfac.hqyj.springBoot.modules.common.entity.ExceptionLog;
import com.sfac.hqyj.springBoot.modules.common.entity.ResultEntity;
import com.sfac.hqyj.springBoot.modules.common.service.ExceptionLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class ExceptionServiceImpl implements ExceptionLogService {
    @Autowired
    private ExceptionLogDao exceptionLogDao;

    @Override
    public ResultEntity<ExceptionLog> insertExceptionLog(ExceptionLog exceptionLog) {
        List<ExceptionLog> exceptionLogs = Optional
                .ofNullable(
                        exceptionLogDao.getExceptionLogsBy(
                                exceptionLog.getPath(), exceptionLog.getExceptionType())
                ).orElse(Collections.emptyList());
        if (exceptionLogs.isEmpty()) {
            exceptionLog.setCreateDate(LocalDateTime.now());
            exceptionLogDao.insertExceptionLog(exceptionLog);
            return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.code,
                    "Insert successs.", exceptionLog);
        }
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.code,
                "Exeption info is exist.", exceptionLog);
    }

    @Override
    public List<ExceptionLog> getExceptionLogsBy(String path, String exceptionType) {
        return exceptionLogDao.getExceptionLogsBy(path, exceptionType);
    }
}
